import React, { } from 'react'
import F2Chart from './chart'
import { ColumnProps } from './type'
import { randomId } from './util'
import * as util from './util'

function draw(chart: any, F2: any, props: ColumnProps): void {
  if (!chart) {
    return
  }
  const { categories, series, xAxis, yAxis, tooltip, legend, adjust, coord } = props
  // console.log('column render', categories, series)

  chart.clear()

  if (!Array.isArray(series) || series.length <= 0) {
    return
  }

  let data: { key: string; value: number; type?: string }[] = []
  if (series.length === 1) {
    data = series[0].data.map((item, i) => {
      return {
        key: categories[i],
        value: item,
        type: series[0].type
      }
    })
  } else if (series.length > 1) {
    series.forEach(kind => {
      data = data.concat(kind.data.map((item, i) => {
        return {
          key: categories[i],
          value: item,
          type: kind.type
        }
      }))
    })
  }
  chart.source(data)

  if (coord) {
    chart.coord(coord)
  }
  if (xAxis) {
    if (xAxis.htAlign) {
      if (!coord || !coord.transposed) {
        xAxis.label = util.label
      } else {
        yAxis.label = util.label
      }
    }
    chart.scale('key', util.scale(xAxis))
    chart.axis('key', util.axis(xAxis, F2))
  }
  if (yAxis) {
    chart.scale('value', util.scale(yAxis))
    chart.axis('value', util.axis(yAxis, F2))
  }
  chart.tooltip(tooltip)
  chart.legend(legend)

  const color = {}
  series.forEach(kind => {
    if (kind.type) {
      color[kind.type] = kind.color
    }
  })

  if (series.length === 1) {
    chart.interval().position('key*value').color('type', type => {
      return color[type]
    }).adjust(adjust)
  } else if (series.length > 1) {
    chart.interval().position('key*value').color('type', type => {
      return color[type]
    }).adjust(adjust)
  }

  chart.render()
}

type OwnProps = ColumnProps

const defaultProps: OwnProps = {
  cn: 'column',
  categories: [],
  series: [],
  xAxis: {
    tickCount: 3
  },
  yAxis: {
    tickCount: 3
  },
  tooltip: false,
  legend: false,
  adjust: 'stack'
}

const onInitChart = (F2, config, props) => {
  const chart = new F2.Chart(config);
  draw(chart, F2, props)
  // 注意：需要把chart return 出来
  return chart;
}

export default function Colunm(props: OwnProps = defaultProps) {
  return (
    <F2Chart id={`column_${randomId()}`} onInit={(f, conf) => onInitChart(f, conf, props)}></F2Chart>
  )
}

Colunm.defaultProps = defaultProps
